package com.zhao.dome01.controller.userController;

import com.zhao.dome01.commen.Result;
import com.zhao.dome01.pojo.dto.CosPlayerEnrollDto;
import com.zhao.dome01.pojo.dto.CosPlayerLoginDto;
import com.zhao.dome01.pojo.entry.CosPlayer;
import com.zhao.dome01.service.CosPlayerService;
import com.zhao.dome01.utils.JwtUtil;
import com.zhao.dome01.utils.TypeChange;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RestController
@RequestMapping("/user")
public class CosPlayerController {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    private final CosPlayerService cosPlayerService;

    public CosPlayerController(CosPlayerService cosPlayerService) {
        this.cosPlayerService = cosPlayerService;
    }

    @PostMapping("/enroll")
    @Operation(summary = "用户注册")
    public Result<CosPlayer> cosPlayerEnroll(@RequestBody CosPlayerEnrollDto cosPlayerEnrollDto){
        log.info("用户注册方法被调用,注册对象心为为:{}",cosPlayerEnrollDto);
        cosPlayerEnrollDto.setEnrollTime(formatter.format(LocalDateTime.now()));
        cosPlayerService.cosPlayerInsert(cosPlayerEnrollDto);
        return Result.success();
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录功能")
    public Result<CosPlayer> cosPlayerLogin(@RequestBody CosPlayerLoginDto cosPlayerLoginDto, HttpServletResponse response){
        CosPlayer cosPlayer = cosPlayerService.selectCosPlayerByUsername(cosPlayerLoginDto.getUsername());
        if (cosPlayer == null){
            // TODO  这里要跑出异常  但我这里就先返回的
            return Result.error("账号错误");
        }
        //TODO 这里还存在一些问题  没有进行登录状态检测
        if (cosPlayer.getPassword().equals(cosPlayerLoginDto.getPassword())){
            //TODO 在这里token令牌依旧有些问题 在这里面还有一些隐私问题的存在
            String token = JwtUtil.createToken(TypeChange.beanToMap(cosPlayer));
            response.setHeader("token",token);
            return Result.success(cosPlayer);
        }
        else {
            return Result.error("密码错误");
        }
    }
}
